package com.dlgcy.weibo;

import java.net.URI;

import net.sf.json.JSONObject;

import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.utils.QHttpClient;

public class Forward {
	static String FILE_PATH = ConfigUtil.FILE_PATH;
		
	static String APP_KEY = ConfigUtil.getValue("APP_KEY");;
	static String APP_SECRET = ConfigUtil.getValue("APP_SECRET");
	static String REDIRECT_URI = ConfigUtil.getValue("REDIRECT_URI");
	public static String ACCESS_TOKEN = ConfigUtil.getValue("ACCESS_TOKEN");
	static String OPEN_ID = ConfigUtil.getValue("OPEN_ID");
	private static OAuthV2 oAuth = new OAuthV2(); // 使用OAuth V2 的 Implicit模式 ;
	static int nSecond = ConfigUtil.getIntValue("nSecond");  //发送间隔（单位：秒）；
	static TAPI tAPI=new TAPI(oAuth.getOauthVersion());//根据oAuth配置对应的连接管理器；
	static UserAPI userAPI = new UserAPI(oAuth.getOauthVersion());

	public static void init() {
		oAuth.setClientId(APP_KEY);
		oAuth.setClientSecret(APP_SECRET);
		oAuth.setRedirectUri(REDIRECT_URI);
		oAuth.setAccessToken(ACCESS_TOKEN);
		oAuth.setOpenid(OPEN_ID);   //发微博时需要！；
		oAuth.setClientIP(API_CLIENTIP);
		oAuth.setOauthVersion("2.a");
		oAuth.setScope("all");  //请求权限范围 ;
		// oAuth.setOpenkey("5651A9639BD8A96BF979AE5DC1D07872");
		// oAuth.setExpiresIn("604800");
	}

	public static void authorize() {// 授权；
		// 自定制http连接管理器
		QHttpClient qHttpClient = new QHttpClient(2, 2, 5000, 5000, null, null);
		OAuthV2Client.setQHttpClient(qHttpClient);
		
		init();
		openBrowser(oAuth); // 调用外部浏览器，请求用户授权，并直接取得AccessToken;

		qHttpClient.shutdownConnection();
	}

	private static void openBrowser(OAuthV2 oAuth) {

		// 合成URL
		String implicitGrantUrl = OAuthV2Client.generateImplicitGrantUrl(oAuth);

		// 调用外部浏览器
		if (!java.awt.Desktop.isDesktopSupported()) {
			System.err.println("Desktop is not supported (fatal)");
			System.exit(1);
		}
		java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
		if (desktop == null || !desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
			System.err.println("Desktop doesn't support the browse action (fatal)");
			System.exit(1);
		}
		try {
			desktop.browse(new URI(implicitGrantUrl));
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public static Boolean isAuthorized(String responseData) {  //判断授权是否成功；

		/*System.out.println("Input the authorization information (eg: access_token=ACCESS_TOKEN&expires_in=60&openid= OPENID &openkey= OPENKEY ) :");
		Scanner in = new Scanner(System.in);
		String responseData = in.nextLine();
		in.close();*/

		if (OAuthV2Client.parseAccessToken(responseData, oAuth)) {
			System.out.println("Get Access Token Successfully");

			// 获取并保存Access Token 等数据 ;
			String accessToken = oAuth.getAccessToken();
			String openId = getOpenId(responseData);
			System.out.println("AccessToken=" + accessToken);
			System.out.println("openId=" + openId);
			ConfigUtil.setValue("ACCESS_TOKEN", accessToken);
			ConfigUtil.setValue("OPEN_ID", openId);
			ConfigUtil.saveFile(FILE_PATH, null);

			return true;
		} else {
			System.out.println("Fail to Get Access Token");
			return false;
		}
	}

	static String getOpenId(String str) {
		String id;
		int start = str.indexOf("openid") + 7;
		int end = str.indexOf("&", start);
		id = str.substring(start, end);
		return id;
	}
	
	public static void sendText(String content){  //发送文本微博；
        //TAPI tAPI=new TAPI(oAuth.getOauthVersion());//根据oAuth配置对应的连接管理器；
		init();
		String response;
		try {
			//response=tAPI.add(oAuth, API_FORMAT_JSON, content+new_Weibo, API_CLIENTIP, jing, wei, syncflag);//测试用；
			response=tAPI.add(oAuth, API_FORMAT_JSON, content, API_CLIENTIP, jing, wei, syncflag);
			isSendSucceed(response);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	public static void sendTextAndPic(String content, String picPath){  //发带图片微博；
       //TAPI tAPI=new TAPI(oAuth.getOauthVersion());//根据oAuth配置对应的连接管理器；
		init();
		String response;
		try {
			//response=tAPI.addPic(oAuth, API_FORMAT_JSON, content+new_Weibo, API_CLIENTIP, jing, wei, picPath, syncflag);//测试用；
			response=tAPI.addPic(oAuth, API_FORMAT_JSON, content, API_CLIENTIP, jing, wei, picPath, syncflag);
			isSendSucceed(response);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	public static String getUserNick(){
		init();
		String response, nick="";
		try {
			response=userAPI.info(oAuth, API_FORMAT_JSON);
			JSONObject responseJsonObject = JSONObject.fromObject(response);
			JSONObject dataJsonObject = (JSONObject)responseJsonObject.get("data");	    
			//System.out.println(response);
			nick = dataJsonObject.get("nick").toString();//得到用户昵称；
			//System.out.println(nick);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nick;
	}
	
	public static Boolean isSendSucceed(String response){
		// json数据使用
        // response的结果可能是这样，{"data":{"id":"90221131024999","time":1333002978},"errcode":0,"msg":"ok","ret":0}
		// 下面的代码将取出 id 的对应值.
		String id = null;
		System.out.println("response = "+response);
		JSONObject responseJsonObject = JSONObject.fromObject(response);
		JSONObject dataJsonObject = (JSONObject)responseJsonObject.get("data");	       
		id = dataJsonObject.get("id").toString();//对后面用到的 id 赋值
		if(id != null){
			System.out.println("发送成功！");
			ConfigUtil.setValueAndSave("new_Weibo", ++new_Weibo + "", Forward.FILE_PATH);  //变量递增；
			try { Thread.sleep ( nSecond * 1000 ) ; } catch (InterruptedException ie){}  //暂时写在这里，防止发表太快导致被限制发表；
			return true;
		}else{
			System.out.println("发送失败！");
			return false;
       }
	}

	/*public static void main(String[] args) {	
		System.out.println(ConfigUtil.getValue("CAN_READ"));
		String picPath = "image/winstart.jpg";
		
		if (Forward.ACCESS_TOKEN == "") {  //若要重新授权，将配置文件中该项删除；
			Forward.init();
			Forward.authorize();
			Forward.isAuthorized();
		} else {
			Forward.init();  //需要的参数赋值；
			Forward.sendText("发一条文本微博");	
			Forward.sendTextAndPic("发一张本地图片", picPath);
			Forward.sendTextAndPic("发一张网络图片", "http://service.t.sina.com.cn/widget/qmd/1698863933/85be6061/7.png");
		}
	}*/
	
	public final static String API_CLIENTIP = "127.0.0.1"; // 发送IP地址，必须为用户侧真实ip，不能为内网ip、以127及255开头的ip; 缺省值为127.0.0.1；
	public final static String API_FORMAT_JSON = "json"; // json的发送格式 ;
	public final static String API_FORMAT_XML = "xml"; // xml的发送格式 ;
	static String jing = "";
    static String wei = "";
    static String syncflag = "1"; //微博同步到空间分享标记 , 1表示不同步；
    static String compatibleflag = "0"; //容错标志；
    static int new_Weibo = ConfigUtil.getIntValue("new_Weibo");  // 因为服务器后台会对微博内容进行判重，所以在重复测试时加上变换部分;
}
